package com.waitingresult;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * @Author: WangShuai
 * @CreateTime: 2022-10-21  14:25
 * @Description:
 * @Version: 1.0
 */
public class IpUtils {
    public static String getServerTrulyIP(){
        return getServerTrulyIP("192.168");
    }
    public static String getServerTrulyIP(String prefix){
        Enumeration<NetworkInterface> networkInterfaces = null;
        try {
            networkInterfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
        while (networkInterfaces.hasMoreElements()){
            NetworkInterface networkInterface = networkInterfaces.nextElement();
            Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
            while(inetAddresses.hasMoreElements()){
                InetAddress inetAddress = inetAddresses.nextElement();
                String hostAddress = inetAddress.getHostAddress();
                if(hostAddress.startsWith(prefix)){
                    return hostAddress;
                }
            }
        }
        return null;
    }
}
